<template>
  <div class="together-detail-view">
    <div class="header">
      <van-nav-bar :title="activity.title" left-text="返回" left-arrow @click-left="goBack" />
    </div>

    <div class="detail-content" :style="{ backgroundImage: `url('${backgroundUrl}')` }" ref="contentRef">
      <!-- 可拖拽图标区 -->
      <div v-for="icon in icons" :key="icon.id" class="draggable-icon"
        :style="{ left: icon.x + 'px', top: icon.y + 'px', width: iconSize + 'px', height: iconSize + 'px' }"
        @pointerdown="startDrag($event, icon.id)">
        <img :src="icon.src" :alt="icon.alt" draggable="false" />
      </div>

      <!-- 底部操作固定 -->
      <div class="bottom-actions" ref="bottomRef">
        <div class="action-btn chat-btn" @click="showToast('聊天功能开发中')">
          <i class="chat-icon"></i>
          <span>聊天</span>
        </div>

        <div class="action-btn add-btn" @click="goCreate">
          <i class="add-icon"></i>
          <span>添置</span>
        </div>
      </div>
    </div>

    <!-- Toast -->
    <div class="toast" v-if="showToastMessage">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';

type IconId = string;
interface DraggableIcon {
  id: IconId;
  src: string;
  alt: string;
  x: number;
  y: number;
}

const router = useRouter();
const route = useRoute();
const activity = ref({
  id: 0,
  title: '',
  time: '',
  location: ''
});

// 可选：放在文件顶部常量区
const WEIGHT_ID: IconId = 'weight'
const WEIGHT_ICON_SRC = '/together/app_1.png'
const WEIGHT_ICON_ALT = '减肥打卡'


// 背景（如需从别处带 bg，可继续用 query 读取）
const backgroundUrl = ref<string>('/together/together_inside.png');

// Toast
const showToastMessage = ref(false);
const toastMessage = ref('');
const showToast = (message: string) => {
  toastMessage.value = message;
  showToastMessage.value = true;
  setTimeout(() => (showToastMessage.value = false), 3000);
};

// 跳转
const goCreate = () => router.push('/together/feature/create');
const goWeightLoss = () => router.push('/together/feature/weightloss');
const goMessageBoard = () => router.push('/together/feature/messageboard');

// 拖拽与布局
const contentRef = ref<HTMLElement | null>(null);
const bottomRef = ref<HTMLElement | null>(null);
const iconSize = 80;

const dragState = ref<{
  activeId: IconId | null;
  startX: number;
  startY: number;
  originX: number;
  originY: number;
  moved: boolean;
}>({
  activeId: null,
  startX: 0,
  startY: 0,
  originX: 0,
  originY: 0,
  moved: false
});
const dragClickThreshold = 6;

const icons = ref<DraggableIcon[]>([
  /* { id: 'weight', src: '/together/app_1.png', alt: '减肥打卡', x: 0, y: 0 }, */
  { id: 'board', src: '/together/app_2.png', alt: '留言板', x: 0, y: 0 },
  { id: 'album', src: '/together/app_3.png', alt: '纪念册', x: 0, y: 0 }
]);

// 存取（按活动 id）
const storageKey = () => `together_icons_pos_${activity.value.id}`;
const savePositions = () => {
  localStorage.setItem(storageKey(), JSON.stringify(icons.value.map(i => ({ id: i.id, x: i.x, y: i.y }))));
};
// 替换原来的 loadPositions
const loadPositions = () => {
  try {
    const raw = localStorage.getItem(storageKey())
    if (!raw) return false

    // 兼容老数据：可能没有 id，只保存了 x/y
    let list: Array<{ id?: IconId; x: number; y: number }> = JSON.parse(raw)

    // 只给第一条“无 id”的记录补上 id = 'weight'
    let assigned = false
    list = list.map((it) => {
      if (!it.id && !assigned) {
        assigned = true
        return { ...it, id: WEIGHT_ID }
      }
      return it as { id: IconId; x: number; y: number }
    })

    // 用 map 方便按 id 合并
    const byId = new Map<IconId, { id: IconId; x: number; y: number }>()
    for (const it of list) {
      if (it.id) byId.set(it.id, it as { id: IconId; x: number; y: number })
    }

    // 1) 先把已存在的图标位置回填
    icons.value = icons.value.map((i) => {
      const m = byId.get(i.id)
      return m ? { ...i, x: m.x, y: m.y } : i
    })

    // 2) 如果本地有 weight 但内存里没有，就动态补一个 weight 图标
    if (byId.has(WEIGHT_ID) && !icons.value.some((i) => i.id === WEIGHT_ID)) {
      const pos = byId.get(WEIGHT_ID)!
      icons.value.push({
        id: WEIGHT_ID,
        src: WEIGHT_ICON_SRC,
        alt: WEIGHT_ICON_ALT,
        x: pos.x,
        y: pos.y,
      })
    }

    return true
  } catch {
    return false
  }
}


// 计算中心（避开底部栏）
function centerPosition() {
  const el = contentRef.value;
  if (!el) return { x: 0, y: 0 };
  const rect = el.getBoundingClientRect();
  const bottomH = bottomRef.value?.offsetHeight ?? 0;
  const safeH = Math.max(0, rect.height - bottomH);
  const cx = Math.round((rect.width - iconSize) / 2);
  const cy = Math.round((safeH - iconSize) / 2);
  return clampToBounds(cx, cy);
}

// 默认布局
const layoutDefaults = () => {
  const el = contentRef.value;
  if (!el) return;
  const rect = el.getBoundingClientRect();
  const padding = 24;
  const bottomH = bottomRef.value?.offsetHeight ?? 0;
  const usableW = Math.max(0, rect.width - padding * 2 - iconSize);
  const usableH = Math.max(0, rect.height - bottomH - iconSize - padding * 2);

  const positions = [
    { x: padding + usableW * 0.5, y: padding + usableH * 0.15 },
    { x: padding + usableW * 0.2, y: padding + usableH * 0.45 },
    { x: padding + usableW * 0.8, y: padding + usableH * 0.45 }
  ];

  icons.value = icons.value.map((i, idx) => ({
    ...i,
    x: Math.round(positions[idx].x),
    y: Math.round(positions[idx].y)
  }));
};

// 边界约束（考虑底部栏）
const clampToBounds = (x: number, y: number) => {
  const el = contentRef.value;
  if (!el) return { x, y };
  const rect = el.getBoundingClientRect();
  const minX = 0;
  const minY = 0;
  const maxX = Math.max(0, rect.width - iconSize);
  const bottomH = bottomRef.value?.offsetHeight ?? 0;
  const maxY = Math.max(0, rect.height - iconSize - bottomH);
  return {
    x: Math.min(Math.max(x, minX), maxX),
    y: Math.min(Math.max(y, minY), maxY)
  };
};

const findIcon = (id: IconId) => icons.value.find(i => i.id === id)!;

// 拖拽
const startDrag = (e: PointerEvent, id: IconId) => {
  const icon = findIcon(id);
  dragState.value.activeId = id;
  dragState.value.startX = e.clientX;
  dragState.value.startY = e.clientY;
  dragState.value.originX = icon.x;
  dragState.value.originY = icon.y;
  dragState.value.moved = false;

  const target = e.currentTarget as HTMLElement;
  target.setPointerCapture(e.pointerId);
  (target as HTMLElement).style.touchAction = 'none';

  window.addEventListener('pointermove', onPointerMove, { passive: false });
  window.addEventListener('pointerup', onPointerUp, { passive: false });
};

const onPointerMove = (e: PointerEvent) => {
  if (!dragState.value.activeId) return;
  e.preventDefault();

  const dx = e.clientX - dragState.value.startX;
  const dy = e.clientY - dragState.value.startY;

  if (!dragState.value.moved && Math.hypot(dx, dy) >= dragClickThreshold) {
    dragState.value.moved = true;
  }

  const icon = findIcon(dragState.value.activeId);
  const { x, y } = clampToBounds(dragState.value.originX + dx, dragState.value.originY + dy);
  icon.x = x;
  icon.y = y;
};

const onPointerUp = () => {
  const id = dragState.value.activeId;
  const moved = dragState.value.moved;
  dragState.value.activeId = null;

  window.removeEventListener('pointermove', onPointerMove);
  window.removeEventListener('pointerup', onPointerUp);

  savePositions();
  if (!moved && id) {
    if (id === 'weight') goWeightLoss();
    else if (id === 'board') goMessageBoard();
    else if (id === 'album') showToast('纪念册功能开发中');
  }
};

// ✅ 进入时“消费” pending 图标：一次性读取并清空
function consumePendingIcon() {
  try {
    const raw = localStorage.getItem('together_pending_new_icon');
    if (!raw) return;
    const data = JSON.parse(raw) as { src: string; alt?: string; ts?: number };
    if (!data?.src) return;

    const pos = centerPosition();
    icons.value.push({
      id: `weight`,
      src: data.src,
      alt: data.alt || '自定义功能',
      x: pos.x,
      y: pos.y
    });

    // 清空一次性消息，并保存新位置
    localStorage.removeItem('together_pending_new_icon');
    savePositions();
    showToast('已为你新增一个图标');
  } catch {
    // ignore
  }
}

onMounted(async () => {
  // 活动基本信息
  const id = route.params.id;
  activity.value = {
    id: Number(id),
    title: '好姐妹就要退休一起住别墅',
    time: '2023-06-10 14:00',
    location: '中央公园'
  };

  // 如果 detail 也可能通过 query 传 bg/title，这里可选读取
  if (typeof route.query.bg === 'string' && route.query.bg) {
    backgroundUrl.value = route.query.bg;
  }
  if (typeof route.query.title === 'string' && route.query.title) {
    activity.value.title = route.query.title;
  }

  await nextTick();

  // 布局/位置
  const ok = loadPositions();
  if (!ok) {
    layoutDefaults();
    savePositions();
  } else {
    // 边界校正
    icons.value = icons.value.map(i => {
      const c = clampToBounds(i.x, i.y);
      return { ...i, ...c };
    });
    savePositions();
  }

  // 🔔 最后：消费 pending 新图标
  consumePendingIcon();
});

// 返回
const goBack = () => router.push('/together');
</script>

<style scoped>
.together-detail-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.15) 0%, rgba(0, 0, 0, 0.05) 50%, rgba(0, 0, 0, 0) 100%);
  padding-bottom: 20px;
}

.header :deep(.van-nav-bar) {
  background: transparent;
  box-shadow: none;
}

.header :deep(.van-nav-bar .van-nav-bar__title),
.header :deep(.van-nav-bar .van-nav-bar__text),
.header :deep(.van-nav-bar .van-icon) {
  color: white;
}

/* 容器 */
.detail-content {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 70px 20px 20px;
  overflow: hidden;
}

/* 可拖拽图标 */
.draggable-icon {
  position: absolute;
  user-select: none;
  touch-action: none;
  cursor: grab;
  display: flex;
  align-items: center;
  justify-content: center;
}

.draggable-icon:active {
  cursor: grabbing;
}

.draggable-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  pointer-events: none;
}

/* 底部操作固定 */
.bottom-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  background-color: rgba(255, 255, 255, 0.1);
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  cursor: pointer;
}

.chat-icon {
  width: 50px;
  height: 50px;
  background-image: url("/together/chat.png");
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  margin-bottom: 5px;
}

.add-icon {
  width: 50px;
  height: 50px;
  background-image: url("/together/add.png");
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  margin-bottom: 5px;
}

.action-btn span {
  font-size: 14px;
  color: #333;
}

/* Toast */
.toast {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, .7);
  color: #fff;
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 100;
  animation: fadeInOut 3s ease;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translate(-50%, 20px);
  }

  15% {
    opacity: 1;
    transform: translate(-50%, 0);
  }

  85% {
    opacity: 1;
    transform: translate(-50%, 0);
  }

  100% {
    opacity: 0;
    transform: translate(-50%, 20px);
  }
}
</style>
